package org.jeecg.modules.voucher.job;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.models.auth.In;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.voucher.entity.Voucher;
import org.jeecg.modules.voucher.service.IVoucherService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import javax.sql.DataSource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
public class VoucherSendJob implements Job {

	@SneakyThrows
    @Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		ISysUserService sysUserService = SpringContextUtils.getApplicationContext().getBean(ISysUserService.class);
		IVoucherService voucherService = SpringContextUtils.getApplicationContext().getBean(IVoucherService.class);
		ISysDictService sysDictService = SpringContextUtils.getApplicationContext().getBean(ISysDictService.class);
		RedisUtil redisUtil = SpringContextUtils.getApplicationContext().getBean(RedisUtil.class);

		List<DictModel> configs = sysDictService.getDictItems("voucher_config");

		String amtValue = "10";
		String days = "30";
		if(CollectionUtil.isNotEmpty(configs)){
			for(DictModel item:configs){
				String key = item.getLabel();
				String val = item.getValue();
				if(StringUtils.equals("amt",key)){
					amtValue = val;
				}else if(StringUtils.equals("days",key)){
					days = val;
				}
			}
		}


		List<SysUser> userList = sysUserService.list(new LambdaQueryWrapper<SysUser>()
				.eq(SysUser::getDelFlag,0).eq(SysUser::getStatus,1)
						.apply("CAST(CONCAT(DATE_FORMAT(NOW(), '%Y'),DATE_FORMAT(birthday,'-%m-%d'))  AS DATETIME ) = CAST( CONCAT(DATE_FORMAT(NOW(), '%Y'),DATE_FORMAT(DATE_ADD(CURRENT_DATE(),INTERVAL 1 DAY),'-%m-%d')) AS DATETIME )"));

		if(CollectionUtil.isNotEmpty(userList)){
			for(SysUser user:userList){
				Voucher voucher = new Voucher();
				voucher.setUseStatus(0);
				voucher.setAmt(new BigDecimal(amtValue));
				voucher.setVoucherType(0);
				voucher.setEffectStartTime(new Date());
				voucher.setEffectEndTime(DateUtils.addDays(new Date(),Integer.parseInt(days)));
				voucher.setName("生日代金券" + amtValue + "元");
				voucher.setSysUserId(user.getId());
				voucherService.save(voucher);
				redisUtil.set("voucher:end:" + voucher.getId(),"",24*60*60* Integer.parseInt(days));
			}
		}
	}
}